export interface TreeNode {
  id: string;
  name: string;
  type?: string;
  description?: string;
  parentId?: string | null;
  required?: boolean;
  level?: number;
  children?: TreeNode[];
  [key: string]: any;
}

/**
 * 平铺树形结构为表格可用的数据格式
 * @param treeData 树形结构数据
 * @returns 扁平化的表格数据
 */
export const flattenTreeToTableData = (treeData: TreeNode[]): any[] => {
  const result: any[] = [];
  
  const traverse = (nodes: TreeNode[], level = 0) => {
    nodes.forEach(node => {
      result.push({
        id: node.id,
        name: node.name,
        type: node.type || '',
        description: node.description || '',
        parentId: node.parentId || null,
        required: node.required || false,
        level,
        key: node.id,
      });
      
      if (node.children && node.children.length > 0) {
        traverse(node.children, level + 1);
      }
    });
  };
  
  traverse(treeData);
  return result;
};

/**
 * 将表格数据转回树形结构
 * @param tableData 扁平表格数据
 * @returns 转换后的树形结构
 */
export const convertTableDataToTree = (tableData: any[]): TreeNode[] => {
  const result: TreeNode[] = [];
  const map: Record<string, TreeNode> = {};
  
  // 第一次遍历，创建所有节点
  tableData.forEach((row) => {
    map[row.id] = {
      id: row.id,
      name: row.name,
      type: row.type,
      description: row.description,
      parentId: row.parentId,
      required: row.required,
      level: row.level,
    };
  });
  
  // 第二次遍历，构建树形结构
  Object.values(map).forEach(node => {
    if (node.parentId && map[node.parentId]) {
      if (!map[node.parentId].children) {
        map[node.parentId].children = [];
      }
      map[node.parentId].children!.push(node);
    } else {
      result.push(node);
    }
  });
  
  return result;
}; 